<?php

namespace App\Model;

/**
 * 存入报价相关
 * FromTradeModel.php
 * @author zhouqiang
 * @date 2018/05/11
 */
class FromTradeModel extends BaseModel
{
    protected $table = 'from_trade';

    protected $primaryKey = 'from_trade_id';

    public static $tradeOfferStatusMap = [
        'success' => 3,                         //报价成功
        'create' => 2,                          //报价已确认
        'canceled' => 6,                        //机器人取消报价
        'user_canceled' => 7,                   //用户取消报价
        'waiting' => -1,                        //报价发起前
        'item_bad' => 8,                        //物品异常，报价重复
        'hang_up' => 11,                        //报价暂挂
        'trade_canceled' => 10,                 //报价已取消
        'trade_create' => 9,                    //发起报价未确认
        'time_out_fail' => -100,                //超时自动取消
        'private_or_limit_fail' => -3,          //无法交易，隐私或限制
        'trade_url_bad_or_user_inv_max' => -2,  //交易链接失效，库存超限，限制
        'trade_rollback' => 4,                  //报价回滚
    ];

    public function fromTradeDetail() {
        return $this->hasMany('App\Model\FromTradeDetailModel', 'from_trade_id', 'from_trade_id');
    }

    /**
     * 创建
     * @param $data
     * @return bool|mixed
     */
    public static function createTradeOffer($data)
    {
        $connection = (new self())->getConnection();
        $connection->beginTransaction();
        try {
            $fromTrade = new self ();
            $fromTrade->bot_id = $data['bot_id'];
            $fromTrade->app_id = $data['app_id'];
            $fromTrade->steam_id = $data['steam_id'];
            $fromTrade->tradeToken = $data['tradeToken'];
            $fromTrade->quantity = $data['quantity'];
            $fromTrade->tradeoffer_status = -1;
            $fromTrade->tradeoffer_id = $data['tradeoffer_id'];
            $fromTrade->tradeoffer = $data['tradeoffer'];
            if (!$fromTrade->save()) {
                $connection->rollBack();
                return false;
            }
            $fromTradeId = $fromTrade->from_trade_id;
            if (!FromTradeDetailModel::createTradeDetail($fromTradeId, $data['detail_items'])) {
                $connection->rollBack();
                return false;
            }
            $connection->commit();
            return $fromTradeId;
        } catch (\Exception $e) {
            echo $e->getMessage();
            $connection->rollBack();
            return false;
        }
    }

    public static function getFromTradeInfo($fromTradeId)
    {
        if(empty($fromTradeId)){
            return false;
        }
        return static::where('from_trade_id', $fromTradeId)->with('fromTradeDetail')->first();
    }

    /**
     * 获取交易报价成功，新物品ID未落地
     * @return array
     */
    public static function getFromTradeForFinish($fromTradeId = 0)
    {
        $where['tradeoffer_status'] = self::$tradeOfferStatusMap['success'];
        $fromTradeId>0 && $where['from_trade_id'] = $fromTradeId;

        $result = static::where($where)
            ->whereHas('fromTradeDetail', function($q) use($fromTradeId){
                $q->where('new_assetid', '=', '');
            })->first();

        return !empty($result) ? $result->toArray() : array();
    }

    /**
     * 获取待检查的报价状态
     * @return array
     */
    public static function getFromTradeByCheckAll()
    {
        $where['tradeoffer_status'] = self::$tradeOfferStatusMap['create'];

        $result = static::where($where)->orWhere(function($query){
            $query->where('tradeoffer_status', self::$tradeOfferStatusMap['hang_up'])
                ->where('escrow_end_date', '>', 0)
                ->where('escrow_end_date', '<', time());
        })->get();

        return !empty($result) ? $result->toArray() : [];
    }

    /**
     * 修改报价状态
     * @param  int $fromTradeId 报价订单ID
     * @param  int $tradeofferStatus 报价状态
     * @return bool
     */
    public static function updateFromTradeState($fromTradeId, $tradeofferStatus)
    {
        $where = array(
            'from_trade_id' => $fromTradeId,
        );

        $field = array(
            'tradeoffer_status' => $tradeofferStatus,
        );

        return static::where($where)->update($field);
    }

    /**
     * 设置暂挂时间
     * @param $userOrderId
     * @param $escrowEndDate
     * @return mixed
     */
    public static function updateFromTradeEscrowDate($fromTradeId, $escrowEndDate)
    {
        $where = array(
            'from_trade_id' => $fromTradeId,
        );

        $field = array(
            'escrow_end_date' => $escrowEndDate
        );

        return static::where($where)->update($field);
    }
}